package com.frank.stock4j.dataloader.abstractloader;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.frank.stock4j.tusharepro.BaseBean;
import com.frank.stock4j.tusharepro.entity.StockBasicEntity;
import com.frank.stock4j.tusharepro.mapper.StockBasicMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class AbstractStockRangeLoader<T extends BaseBean, E extends BaseMapper<T>> extends AbstractLoader<T, E> {

    String conditionName = "primary_id";

    @Autowired
    StockBasicMapper mapper;

    public abstract Integer getStockSize();

    @Override
    public List<T> load() {
        Map<String, Object> cursorMap = this.getCursor();
        Integer id = 0;
        if (!ObjectUtils.isEmpty(cursorMap)) {
            id = (Integer) cursorMap.get(conditionName);
        }
        QueryWrapper<StockBasicEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc(conditionName);
        wrapper.gt(conditionName, id);
        List<StockBasicEntity> list = mapper.selectList(wrapper);
        StringBuilder codeBuilder = new StringBuilder();
        for (int i = 1; i < list.size() + 1; i++) {
            StockBasicEntity stock = list.get(i - 1);
            codeBuilder.append(stock.getTsCode()).append(",");
            if (i % getStockSize() == 0 || i == list.size()) {
                if (stoped) {
                    return null;
                }
                ;
                this.param("ts_code", codeBuilder.substring(0, codeBuilder.length() - 1));
                super.innerLoad();
                codeBuilder = new StringBuilder();
                if (ObjectUtils.isEmpty(cursorMap)) {
                    cursorMap = new HashMap<>();
                }
                cursorMap.put(conditionName, stock.getPrimaryId());
                this.setCursor(cursorMap);
            }
        }
        return null;
    }
}
